package com.huawei.knowledge.cfg;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

@ControllerAdvice
public class GlobalExceptionResolver extends ResponseEntityExceptionHandler {

    private Logger myLogger = LogManager.getLogger(GlobalExceptionResolver.class);


    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public String jsonHandler(HttpServletRequest request, Exception e) throws Exception {
        log(e, request);


        return e.getMessage();
    }

    private void log(Exception ex, HttpServletRequest request) {
        logger.error("************************异常开始*******************************");
        logger.error(ex);
        logger.error("请求地址：" + request.getRequestURL());
        Enumeration enumeration = request.getParameterNames();
        logger.error("请求参数");
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement().toString();
            logger.error(name + "---" + request.getParameter(name));
        }

        logger.error("eror : ",ex);
        logger.error("************************异常结束*******************************");
    }
}